package com.whty.cms.filewps.util;

import com.danga.MemCached.MemCachedClient;
import com.whty.cms.filewps.config.dto.Configure;
import com.whty.cms.filewps.config.service.IConfigureService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class MemcacheUtil {

	private static final Logger logger = LogManager.getLogger(MemcacheUtil.class);
	
	private static MemCachedClient memCachedClient = (MemCachedClient) SpringUtils.getBean("memCachedClient");
	
	private static IConfigureService configureService = (IConfigureService) SpringUtils.getBean("configureService");
	
	
	/**
	 * 添加数据到memcache缓存
	 * @param key
	 * @param obj
	 * @return
	 */
	public static boolean putObj(String key, Object obj, int secs) {
		boolean ret = false;
		try {
			long currentTime = secs * 1000;
			ret = memCachedClient.set(key, obj,  new Date(currentTime));
		} catch(Exception ex) {
			logger.error("添加memcache缓存数据错误:", ex);
		}
		return ret;
	}
	
	public static boolean putAll() {
		boolean ret = false;
		try {
			
			List<Configure> list = configureService.selectAll();
	        for(Configure con : list) {
	        	putObj(con.getKey(),con.getValue(), 24*60*60);
	        }
		} catch(Exception ex) {
			logger.error("添加memcache缓存数据错误:", ex);
		}
		return ret;
	}
	
	/**
	 * 获取memcache缓存数据
	 * @param key
	 * @return
	 */
	public static Object getObj(String key) {
		Object obj = null;
		try {
			obj = memCachedClient.get(key);
		} catch(Exception ex) {
			logger.error("获取memcache缓存数据错误:", ex);
		}
		return obj;
	}
	
	/**
	 * 获取数据库配置表的缓存数据，如果为空则将配置表的数据重新写入缓存
	 * @param key
	 * @return
	 */
	public static String getDatabaseObj(String key) {
		String obj = null;
		try {
			obj = (String) memCachedClient.get(key);
			if(obj==null) {
				putAll();
				obj = (String) memCachedClient.get(key);
			}
		} catch(Exception ex) {
			logger.error("获取memcache缓存数据错误:", ex);
		}
		return obj;
	}
	
	/**
	 * 批量获取memcache缓存数据
	 * @param keys
	 * @return
	 */
	public static Map<String, Object> getObjs(String[] keys) {
		Map<String, Object> objs = null;
		try {
			objs = memCachedClient.getMulti(keys);
		} catch(Exception ex) {
			logger.error("批量获取memcache缓存数据错误:", ex);
		}
		return objs;
	}

	
	/**
	 * 删除memcache缓存数据
	 * @param key
	 * @return
	 */
	public static boolean delObj(String key) {
		boolean ret = false;
		try {
			ret = memCachedClient.delete(key);
		} catch(Exception ex) {
			logger.error("删除memcache缓存数据错误:", ex);
		}
		return ret;
	}
	
	/**
	 * @author	xiongxiaofei
	 * @date	2015年5月7日
	 * @desc	清空memcache缓存
	 */
	public static void flushAll() {
		try {
			memCachedClient.flushAll();
		} catch(Exception ex) {
			logger.error("清空memcache缓存出错：", ex);
		}
	}
	
}
